<template>
  <u-popup 
    :show="show" 
    @close="onClose"
    mode="bottom"
    :round="20"
    :closeable="false"
  >
    <view class="region-picker">
      <!-- 头部 -->
      <view class="picker-header">
        <text class="cancel-btn" @click="onCancel">取消</text>
        <text class="title">选择地域</text>
        <text class="confirm-btn" @click="onConfirm">确定</text>
      </view>
      
      <!-- 内容区域 -->
      <view class="picker-content">
        <!-- 左侧区域列表 -->
        <scroll-view class="region-list" scroll-y="true">
          <view 
            v-for="region in regions" 
            :key="region.id"
            class="region-item"
            :class="{ active: selectedRegion === region.id }"
            @click="selectRegion(region.id)"
          >
            <text class="region-name">{{ region.name }}</text>
          </view>
        </scroll-view>
        
        <!-- 右侧城市列表（可滚动） -->
        <scroll-view class="city-list" scroll-y="true">
          <view 
            v-for="city in currentCities" 
            :key="city.id"
            class="city-item"
            :class="{ 
              active: selectedCity === city.id,
              disabled: city.count === 0 
            }"
            @click="selectCity(city.id)"
          >
            <text class="city-name">{{ city.name }}<template v-if="city.count !== undefined && city.count !== null && city.count !== ''"></template></text>
          </view>
        </scroll-view>
      </view>
    </view>
  </u-popup>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { systemApi } from '@/api/api-helper.js'

const props = defineProps({
  show: Boolean,
  modelValue: {
    type: String,
    default: ''
  },
  type: {
    type: Number,
    default: 2 // 默认查询省市
  }
})

const emit = defineEmits(['update:show', 'update:modelValue', 'confirm'])

// 区域数据（接口填充）
const regions = ref<{ id: string, name: string }[]>([{ id: 'all', name: '全部' }])

// 城市數據映射
const citiesData = ref<Record<string, { id: string; name: string; count: number }[]>>({ all: [] })

const selectedRegion = ref('all')
const selectedCity = ref<string>('')

// 当前显示的城市列表
const currentCities = computed(() => {
  if (selectedRegion.value === 'all') {
    return [{ id: '', name: '全部', count: undefined }]
  }
  return citiesData.value[selectedRegion.value] || []
})

function onClose() {
  emit('update:show', false)
}

function onCancel() {
  emit('update:show', false)
}

function onConfirm() {
  // 「全部」時傳空值
  const value = selectedRegion.value === 'all' ? '' : selectedCity.value
  const provinceId = selectedRegion.value === 'all' ? '' : selectedRegion.value
  const cityId = value
  const cityName = selectedRegion.value === 'all' ? '全部' : (currentCities.value.find(c => c.id === cityId)?.name || '')
  emit('update:modelValue', value)
  emit('confirm', { provinceId, cityId, cityName })
  emit('update:show', false)
}

function selectRegion(regionId: string) {
  selectedRegion.value = regionId
  // 切换区域时清空已选城市
  selectedCity.value = ''
}

function selectCity(cityId: string) {
  const city = currentCities.value.find(c => c.id === cityId)
  if (!city || city.count === 0) return
  
  selectedCity.value = cityId
}

// 监听外部传入的选中值
watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    selectedCity.value = newValue
  }
}, { immediate: true })

// 初始化：調用地域列表接口
onMounted(async () => {
  try {
    const res: any = await systemApi.getAllProByMapList(props.type)
    if (res && res.code === 200) {
      const list = Array.isArray(res.data) ? res.data : []
      // 后端为扁平结构：{ id, fullName, parentId }；parentId = '-1' 为省，否则为市（其 parentId 指向对应省）
      const provinces = list.filter((item: any) => String(item.parentId) === '-1')
      const regionItems: { id: string; name: string }[] = [{ id: 'all', name: '全部' }]
      const citiesMap: Record<string, { id: string; name: string; count: number }[]> = { all: [] }

      provinces.forEach((prov: any) => {
        const provId = String(prov.id)
        regionItems.push({ id: provId, name: prov.fullName || prov.name || '' })
        const cities = list.filter((c: any) => String(c.parentId) === provId)
        citiesMap[provId] = cities.map((c: any) => ({
          id: String(c.id),
          name: c.fullName || c.name || '',
          count: 1 // 接口无数量，设置为1避免禁用
        }))
        citiesMap.all.push(...citiesMap[provId])
      })

      regions.value = regionItems
      citiesData.value = citiesMap
    }
  } catch (e) {
    console.warn('获取地域列表失败:', e)
  }
})
</script>

<style lang="scss" scoped>
.region-picker {
  background-color: #F8F8F8;
  border-radius: 20rpx 20rpx 0 0;
  min-height: 800rpx;
  height: 70vh;
}

.picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #EEEEEE;
  
  .cancel-btn {
    font-size: 28rpx;
    color: #666666;
  }
  
  .title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
  }
  
  .confirm-btn {
    font-size: 28rpx;
    color: var(--u-primary);
    font-weight: 500;
  }
}

.picker-content {
  display: flex;
  height: 1000rpx;
  background-color: #F8F8F8;
}

.region-list {
  width: 220rpx;
  background-color: #FFFFFF;
  height: 100%; /* 与内容区高度一致 */
  
  .region-item {
    padding: 35rpx 25rpx;
    background-color: #FFFFFF;
    
    .region-name {
      font-size: 30rpx;
      color: #666666;
    }
    
    &.active {
      background-color: #F8F8F8;
      
      .region-name {
        color: var(--u-primary);
        font-weight: 500;
      }
    }
  }
}

.city-list {
  flex: 1;
  padding: 25rpx;
  max-height: 750rpx; /* 与内容区一致，保证可滚动 */
  overflow-y: scroll;
  
  .city-item {
    padding: 30rpx 25rpx;
    
    .city-name {
      font-size: 30rpx;
      color: #333333;
    }
    
    &.active {
      .city-name {
        color: var(--u-primary);
        font-weight: 500;
      }
    }
    
    &.disabled {
      .city-name {
        color: #CCCCCC;
      }
    }
  }
}
</style> 